from flask import Blueprint, request

from config.config import FILE_UPLOAD_PATH, FILE_OUTPUT_PATH
from schedule.tasks import addTemplateViewGenerateTask, app
from service.ffmpeg_core import *
from celery.result import AsyncResult

ffmpeg_bp = Blueprint('ffmpeg', __name__)


# BASE_DIR = os.path.dirname(os.path.dirname(__file__)) + "/file/"

# 获取视频基础信息
@ffmpeg_bp.route('/getVideoInfo')
def video_info():
    # 从查询参数中获取 video_path
    video_path = request.args.get('video_path')
    if not video_path:
        return {"error": "Missing 'videoName' parameter"}, 400
    video_path = get_final_input_path(video_path)

    return get_video_info(video_path)


# 分割视频，按照秒：开始时间，结束时间
@ffmpeg_bp.route('/trimVideo', methods=['POST'])
def trim_video_by_time():
    request_json = request.get_json()
    video_path = get_final_input_path(request_json['video_path'])

    trim_video(
        video_path,
        get_final_output_path(request_json['output_path']),
        request.json['start_time'],
        request.json['end_time']
    )
    return "success"


# 分离视频和音频
@ffmpeg_bp.route('/separateMedia', methods=['POST'])
def separate_media():
    request_json = request.get_json()
    video_path = get_final_input_path(request_json['video_path'])
    video_output_path = get_final_output_path(request_json['video_output_path'])
    audio_output_path = get_final_output_path(request_json['audio_output_path'])

    separate_media(video_path, video_output_path, audio_output_path)
    return "success"


# 生成模版视频
@ffmpeg_bp.route('/generateTemplateVideo', methods=['POST'])
def generate_template_video():
    request_json = request.get_json()
    # 添加任务到任务队列
    result = addTemplateViewGenerateTask.delay(request_json['template_type'], request_json)
    return result.id


# 查询模版视频任务结果
@ffmpeg_bp.route('/getTaskResult/<task_id>')
def get_task_result(task_id):
    asy = AsyncResult(id=task_id, app=app)
    return {
        "status": asy.status,
        "ready": asy.ready(),  # 是否完成
        "result": None if not asy.ready() else asy.result  # 完成后才返回结果
    }


def get_final_input_path(video_path):
    return os.path.join(FILE_UPLOAD_PATH, video_path)


def get_final_output_path(video_path):
    return os.path.join(FILE_OUTPUT_PATH, video_path)
